package com.yangjun.controller.realtimeLiveAnalysis.realtimeSource;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.common.realtimesource.ChartDefine;
import com.yangjun.dao.impl.realtimeLiveAnalysis.realtimeSource.WebImpl;
import com.yangjun.dao.mybatis.mapper.realtimeLiveAnalysis.ChannelInforMapper;
import com.yangjun.dao.mybatis.mapper.realtimeLiveAnalysis.KeywordInforMapper;
import com.yangjun.dao.mybatis.mapper.realtimeLiveAnalysis.RegionInforMapper;
import com.yangjun.entity.realtimeliveAnalysis.ChannelInforEntity;
import com.yangjun.entity.realtimeliveAnalysis.KeywordInforEntity;
import com.yangjun.entity.realtimeliveAnalysis.RegionInforEntity;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.utils.EchartUtils;

@Controller
@RequestMapping("/realtimesource")
public class WebController {
	
	@Autowired
    private ChannelInforMapper mMapper;
	
	@Autowired
    private KeywordInforMapper mKeywordInforMapper;
	
	@Autowired
    private RegionInforMapper mRegionInforMapper;
	
	@Autowired
    WebImpl mModel;
	
	
	/**
	 * 渠道流量表格
	 * @param response
	 * @param pageNum
	 * @param pageSize
	 * @param today
	 * @param contrastday
	 * @param platform	平台字符串
	 * @param channelName	一级渠道
	 * @return
	 */
    @RequestMapping("/getChannelTable")
    @ResponseBody
    public PageInfo<ChannelInforEntity> getTableData(HttpServletResponse response, 
    													@RequestParam(value = "pageNum", required = true) String pageNum,
    													@RequestParam(value = "pageSize", required = true) String pageSize, 
    													@RequestParam(value = "today", required = false) String today,
    													@RequestParam(value = "contrastday", required = false) String contrastday, 
    													@RequestParam(value = "platformstr", required = true) String platform,
    													@RequestParam(value = "firstChannelName", required = true) String channelName) {
    	response.setHeader("Access-Control-Allow-Origin", "*");

    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize), true, true, true);
    	Map<String, String> map = new HashMap<String, String>();
    	map.put("platform", platform);
    	map.put("channel", channelName);
    	map.put("today", today);
    	PageInfo<ChannelInforEntity> page = new PageInfo<ChannelInforEntity>(mMapper.select(map));
    	
    	return page;
    }
    
    /**
     * http://192.168.7.32:8080/realtimesource/platform?platformstr=1&today=2016-11-05&contrastday=2016-11-04
     * 平台流量
     * 耗时1.3s需要缓存
     * @param response
     * @param today
     * @param contrastday
     * @param platformstr 平台字符串
     * @param firstChannelName	一级渠道
     * @param updateCache
     * @return
     */
    @RequestMapping("/platform")
    @ResponseBody
    public Map<String,Object>  platform(HttpServletResponse response,
			@RequestParam(value = "today", required = false) String today,
			@RequestParam(value = "contrastday", required = false) String contrastday, 
			@RequestParam(value = "platformstr", required = false) String platformstr) {
    	if (response != null)
    		response.setHeader("Access-Control-Allow-Origin", "*");
    	
    	// 参数异常处理
    	if (StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	if (StringUtils.isBlank(platformstr))
    		platformstr = "1";
    	
    	String yesterday = DvDateUtils.getDate(new Date(), -1);
    	
    	Map<String, Object> resultMap=null;

    	String key = "platform_" + today +"_"+ platformstr;
//    	System.out.println("key=="+key);
    	
//    	resultMap = (Map<String, Object>) mCache.get(key);
    	
    	if (resultMap==null || resultMap.size()<1) {
    		
//    		System.err.println("platform 缓存为空");
    		 resultMap=new HashMap<String, Object>();
        	String[] platforms = new String[]{};
        	if (StringUtils.isNotBlank(platformstr)) {
        		platformstr = platformstr.replace(" ","");
        		platforms = platformstr.split(",");
        	}
        	
        	List<Map<String, Object>> dataList = mModel.getPlatformOverview(today,yesterday, contrastday, Arrays.asList(platforms));
        	
        	resultMap = EchartUtils.resultMap(today, yesterday, contrastday, dataList);
        	// 获取平台流量折线图
//        	System.out.println("日期--"+today+"对比日--"+contrastday);
        	String[] lineCharts = ChartDefine.getPlatformLineCharts();
        	for (int i = 0; i < lineCharts.length; i ++) {
        		resultMap.put(lineCharts[i], getLineChartMap(lineCharts[i], today, contrastday, Arrays.asList(platforms), null, null, null));
        		
        	}
    	}
    	
    	return resultMap;
    }
    
    /**
     * 渠道流量
     * @param response
     * @param today
     * @param contrastday
     * @param platformstr		平台字符串
     * @param firstChannelName 	一级渠道
     * @return
     */
    @RequestMapping("/channel")
    @ResponseBody
    public Map<String,Object> channel(HttpServletResponse response,
			@RequestParam(value = "today", required = false) String today,
			@RequestParam(value = "contrastday", required = false) String contrastday, 
			@RequestParam(value = "platformstr", required = false) String platformstr,
			@RequestParam(value = "firstChannelName", required = false) String firstChannelName) {   
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	Map<String, Object> resultMap = Maps.newHashMap();
    	
    	// 参数异常处理
    	if (StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	String yesterday = DvDateUtils.getDate(new Date(), -1);
    	
    	
    	
    	if (StringUtils.isBlank(platformstr))
    		platformstr = "1";
    	if (StringUtils.isBlank(firstChannelName))
    		firstChannelName = "seo";
    	
    	String[] platforms = new String[]{};
    	if (StringUtils.isNotBlank(platformstr)) {
    		platformstr = platformstr.replace(" ","");
    		platforms = platformstr.split(",");
    	}
    	
    	List<Map<String, Object>> dataList = mModel.getChannelOverview(today,yesterday, contrastday, Arrays.asList(platforms), firstChannelName);
    	resultMap = EchartUtils.resultMap(today, yesterday, contrastday, dataList);
    	return resultMap;
    }
    
    /**
     * 耗时602毫秒 需要缓存
     * 渠道流量板块：访客折线图
     * @param response
     * @param today
     * @param contrastday
     * @param platformstr		平台字符串
     * @param firstChannelName	一级渠道
     * @param secondChannelName	二级渠道
     * @return
     */
    @RequestMapping("/channelVisitLineChart")
    @ResponseBody
    public Map<String,Object> visitLineChart(HttpServletResponse response,
			@RequestParam(value = "today", required = false) String today,
			@RequestParam(value = "contrastday", required = false) String contrastday, 
			@RequestParam(value = "platformstr", required = false) String platformstr,
			@RequestParam(value = "firstChannelName", required = false) String firstChannelName,
			@RequestParam(value = "secondChannelName", required = false) String secondChannelName ) {
    	  	
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	
    	Map<String, Object> result = Maps.newHashMap();

    	// 参数异常处理
    	if (StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	if (StringUtils.isBlank(platformstr))
    		platformstr = "1";
    	if (StringUtils.isBlank(firstChannelName))
    		firstChannelName = "seo";
    	
    	String[] platforms = new String[]{};
    	if (StringUtils.isNotBlank(platformstr)) {
    		platformstr = platformstr.replace(" ","");
    		platforms = platformstr.split(",");
    	}
    	
    	// 获取渠道访客折线图
    	String[] lineCharts = {ChartDefine.CLIENT_NUMBER, ChartDefine.NEW_CLIENT, ChartDefine.OLD_CLIENT, ChartDefine.JUMP_RATE, ChartDefine.NEW_CLIENT_RATE};
    	for (int i = 0; i < lineCharts.length; i ++) {
    		result.put(lineCharts[i], getLineChartMap(lineCharts[i], today, contrastday, Arrays.asList(platforms), firstChannelName, secondChannelName, null));
    	}
    	
    	return result;
    }
    
    /**
     * 返回折线图数据
     * @param yAxis			竖坐标名称（对应SQL的指标名称）
     * @param today
     * @param contrastday
     * @param ordersources	平台名称
     * @param firstChannel	一级渠道
     * @param secondChannel	二级渠道
     * @param landpage		登录页
     * @return
     */
    private Map<String, Object> getLineChartMap(String yAxis, String today, String contrastday, List<String> ordersources, String firstChannel, String secondChannel, String landpage) {
    	String[] todayHourDataArr = new String[24];
        String[] contrastdayHourDataArr = new String[24];
        Map<String,Object> itemMap = Maps.newHashMap();
        List<Map<String,Object>> querylist = null;
        
        querylist = mModel.getLineChartData(yAxis, today, contrastday, ordersources, firstChannel, secondChannel, landpage); 
        
        for(Map<String,Object> map : querylist){
            String day = String.valueOf(map.get("dataDate"));
            String hour = String.valueOf(map.get("dataHour"));
            
            if (day.equals(today)) {
                todayHourDataArr[Integer.parseInt(hour)] = String.valueOf(map.get(yAxis));
            }else{
            	contrastdayHourDataArr[Integer.parseInt(hour)] = String.valueOf(map.get(yAxis));
            }
            
        }
        
        itemMap.put("name", ChartDefine.getPlatformLineChartDesc(yAxis));
        itemMap.put("legend",DVConstants.REALTIME_CHART_LEGEND);
        itemMap.put("xAxis", DVConstants.TWENTY_FOUR_HOURS_XAXIS);
        itemMap.put("today", todayHourDataArr);
        itemMap.put("contrastday", contrastdayHourDataArr);
        return itemMap;
    }
    
    /**
     * 来源关键词
     * @param response
     * @param pageNum
     * @param pageSize
     * @param today
     * @param contrastday
     * @param platformstr		平台名称
     * @param firstChannelName	一级渠道
     * @param secondChannelName	二级渠道
     * @return
     */
    @RequestMapping("/getKeywordTable")
    @ResponseBody
    public Map<String, Object> getKeywordTable(HttpServletResponse response, 
    													@RequestParam(value = "pageNum", required = true) String pageNum,
    													@RequestParam(value = "pageSize", required = true) String pageSize, 
    													@RequestParam(value = "today", required = false) String today,
    													@RequestParam(value = "contrastday", required = false) String contrastday, 
    													@RequestParam(value = "platformstr", required = true) String platformstr,
    													@RequestParam(value = "firstChannelName", required = true) String firstChannelName,
    													@RequestParam(value = "secondChannelName", required = true) String secondChannelName) {
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	
    	Map<String, Object> result = new HashMap<String, Object>();
    		
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize), true, true, true);
    	Map<String, String> map = new HashMap<String, String>();
    	PageInfo<KeywordInforEntity> page;
    	if (StringUtils.isBlank(platformstr))
    		platformstr = null;
    	if (StringUtils.isBlank(firstChannelName))
    		firstChannelName = null;
    	if (StringUtils.isBlank(secondChannelName))
    		secondChannelName = null;
    	map.put("platform", platformstr);
    	map.put("firstChannel", firstChannelName);
    	map.put("secondChannel", secondChannelName);
    	page = new PageInfo<KeywordInforEntity>(mKeywordInforMapper.select(map));
    	result.put("page", page);
    	result.put("MaxVisiter", mModel.getKeywordMaxVisitor(today, contrastday, platformstr, firstChannelName, secondChannelName));
    	return result;
    }
    
    /**
     * http://192.168.7.32:8080/realtimesource/getRegionTable?pageNum=1&pageSize=10&platformstr=1&firstChannelName=seo&keyword=当归
     * 来源关键词-地域
     * @param response
     * @param pageNum
     * @param pageSize
     * @param today
     * @param contrastday
     * @param platformstr		平台名称
     * @param firstChannelName	一级渠道
     * @param secondChannelName	二级渠道
     * @param keyword			关键词
     * @return
     */
    @RequestMapping("/getRegionTable")
    @ResponseBody
    public Map<String, Object> getRegionTable(HttpServletResponse response, 
    													@RequestParam(value = "pageNum", required = true) String pageNum,
    													@RequestParam(value = "pageSize", required = true) String pageSize, 
    													@RequestParam(value = "today", required = false) String today,
    													@RequestParam(value = "contrastday", required = false) String contrastday, 
    													@RequestParam(value = "platformstr", required = true) String platformstr,
    													@RequestParam(value = "firstChannelName", required = true) String firstChannelName,
    													@RequestParam(value = "secondChannelName", required = false) String secondChannelName, 
    													@RequestParam(value = "keyword", required = true) String keyword) {
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	Map<String, Object> result = new HashMap<String, Object>();
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize), true, true, true);
    	Map<String, String> map = new HashMap<String, String>();
    	
    	if (StringUtils.isBlank(platformstr))
    		platformstr = null;
    	
    	if (StringUtils.isBlank(firstChannelName))
    		firstChannelName = null;
    	
    	if (StringUtils.isBlank(secondChannelName))
    		secondChannelName = null;
    	
    	if (StringUtils.isBlank(keyword))
    		keyword = null;

    	map.put("platform", platformstr);
    	map.put("firstChannel", firstChannelName);
    	map.put("secondChannel", secondChannelName);
    	map.put("keyWord", keyword);
    	
    	List<RegionInforEntity> regionList = mRegionInforMapper.select(map);
    	PageInfo<RegionInforEntity> page = new PageInfo<RegionInforEntity>(regionList);
    	
    	result.put("page", page);
    	result.put("MaxVisiter", mModel.getRegionMaxVisitor(today, contrastday, platformstr, firstChannelName, secondChannelName, keyword));
    	
    	return result;
    }
    
    /**
     * 着陆页
     * @param response
     * @param today
     * @param contrastday
     * @param platformstr		平台名称
     * @param firstChannelName	一级渠道
     * @param secondChannelName	二级渠道
     * @param landpage			着陆页
     * @return
     */
    @RequestMapping("/landpage")
    @ResponseBody
    public Map<String,Object> landpage(HttpServletResponse response,
			@RequestParam(value = "today", required = false) String today,
			@RequestParam(value = "contrastday", required = false) String contrastday, 
			@RequestParam(value = "platformstr", required = false) String platformstr,
			@RequestParam(value = "firstChannelName", required = false) String firstChannelName, 
			@RequestParam(value = "secondChannelName", required = false) String secondChannelName, 
			@RequestParam(value = "landpage", required = false) String landpage) {
    	
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	Map<String, Object> result = Maps.newHashMap();
    	
    	// 参数异常处理
    	if (StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	if (StringUtils.isBlank(platformstr))
    		platformstr = "1";
    	if (StringUtils.isBlank(firstChannelName))
    		firstChannelName = "seo";
    	
    	String[] platforms = new String[]{};
    	if (StringUtils.isNotBlank(platformstr)) {
    		platformstr = platformstr.replace(" ","");
    		platforms = platformstr.split(",");
    	}
    	
    	// 总览数据
    	List<Map<String, Object>> dataList = mModel.getLandpageOverview(today, contrastday, Arrays.asList(platforms), firstChannelName, landpage);
    	if (dataList.size() == 1) {
    		result.put("yesterday", null);
		   	result.put("today", dataList.get(0));
    	} else if (dataList.size() > 1) {
    		result.put("yesterday", dataList.get(0));
		   	result.put("today", dataList.get(1));
	   	} else {
	   		result.put("yesterday", null);
	   		result.put("today", null);
	   	}
    	
    	// 登录页跳出率
    	List<Map<String, Object>> landpagejumpRates = mModel.getLandpageJumpRate(today, contrastday, Arrays.asList(platforms), firstChannelName, secondChannelName);
    	result.put("landpageJumprate", landpagejumpRates);
    	System.out.println("landpagejumRates = " + landpagejumpRates);
    	
    	// 饼图
    	result.put("clientPartition", mModel.getClientProportion(today, contrastday, Arrays.asList(platforms), firstChannelName, secondChannelName));
    	
    	// 折线图
    	String[] lineCharts = {ChartDefine.CLIENT_NUMBER, ChartDefine.NEW_CLIENT, ChartDefine.JUMP_RATE};
    	for (int i = 0; i < lineCharts.length; i ++) {
    		result.put(lineCharts[i], getLineChartMap(lineCharts[i], today, contrastday, Arrays.asList(platforms), firstChannelName, secondChannelName, landpage));
    	}

    	return result;
    }
}


















